package rpc

import (
	"fmt"

	iRrpc "core/contract/grpc"
	enumGrpc "core/enum/grpc"
	"core/grpc/account"
	"core/model/config"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

type Factory struct {
	clients  map[enumGrpc.Value]*grpc.ClientConn
	services map[enumGrpc.Value]interface{}
}

func (f Factory) Build(value enumGrpc.Value) interface{} {
	client, ok := f.services[value]
	if !ok {
		panic(fmt.Sprintf("无效rpc服务:%v", value))
	}

	return client
}

func (f Factory) Close() error {
	for _, conn := range f.clients {
		err := conn.Close()
		if err != nil {
			return err
		}
	}
	return nil
}

func NewRpcFactory(config *config.Config) (iRrpc.IGrpcFactory, func() error, error) {
	wrapper := &Factory{
		clients:  make(map[enumGrpc.Value]*grpc.ClientConn),
		services: make(map[enumGrpc.Value]interface{}),
	}

	creds := insecure.NewCredentials()
	for _, v := range config.Rpc {
		// 建立与服务器的连接
		conn, err := grpc.NewClient(v.Addr, grpc.WithTransportCredentials(creds))
		if err != nil {
			return nil, nil, fmt.Errorf("did not connect to %s: %v", v.Name, err)
		}

		// 根据服务名称创建对应的服务客户端
		var client interface{}
		switch v.Name {
		case enumGrpc.Admin:
			client = account.NewGreeterClient(conn)
		// 这里可以根据实际需要添加更多的服务类型及对应的创建逻辑
		default:
			return nil, nil, fmt.Errorf("unsupported service type: %s", v.Name)
		}

		wrapper.clients[v.Name] = conn
		wrapper.services[v.Name] = client
	}

	return wrapper, wrapper.Close, nil
}
